<%@ WebHandler Language="C#" Class="IPv4Country" %>

using System;
using System.Web;
using U2;
using System.Collections.Generic;
using System.Linq;

public class IPv4Country : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        // 請到 https://db-ip.com/db/download/ip-to-country-lite 下載 csv
        // 把資料 寫到 ~/App_Data/dbip-country.csv

        context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");

        if (context.Request.QueryString["pass"] != "zxp09")
        {
            context.Response.Write("需密碼才能完成此操作");
            return;
        }

        string data = UW.FileUtil.TextFromFile(context.Server.MapPath("~/App_Data/dbip-country.csv"));
        List<string> listOfLine = data.Replace("\r", "").Split('\n').ToList();

        U2.SQL.ExecuteSQL("Truncate Table [IPv4Country]");

        context.Response.Write("Total:" + listOfLine.Count + ", start: " + DateTime.Now.ToString() + "\r\n");
        int intCount = 0;
        List<string> sqls = new List<string>();
        foreach (string line in listOfLine)
        {
            if (line.Trim().Length == 0)
            {
                continue;
            }

            var mydata = line.Replace("\"", "").Split(',');
            if (mydata[0].IndexOf(":") >= 0)
            {
                continue;
            }

            intCount++;

            string[] IpStart = mydata[0].Split('.');
            long iStart = Convert.ToInt64(Math.Pow(256L, 3L)) * Convert.ToInt64(IpStart[0]) + Convert.ToInt64(Math.Pow(256L, 2L)) * Convert.ToInt64(IpStart[1]) + 256L * Convert.ToInt64(IpStart[2]) + Convert.ToInt64(IpStart[3]);
            string[] IpEnd = mydata[1].Split('.');
            long iEnd = Convert.ToInt64(Math.Pow(256L, 3L)) * Convert.ToInt64(IpEnd[0]) + Convert.ToInt64(Math.Pow(256L, 2L)) * Convert.ToInt64(IpEnd[1]) + 256L * Convert.ToInt64(IpEnd[2]) + Convert.ToInt64(IpEnd[3]);

            sqls.Add("IPv4Country".SQL().InsertBuilder()
                .Set("IpStart", iStart).Set("IpEnd", iEnd)
                .Set("Country", mydata[2])
                .Set("IPRange", mydata[0]+ "-" + mydata[1])
                .Sql);
            if (sqls.Count >= 100)
            {
                try
                {
                    U2.SQL.ExecuteSQL(string.Join("", sqls));
                }
                catch (Exception ex)
                {
                    context.Response.Write("error: " + ex.Message + "\r\n" + line + "\r\n");
                    //throw;
                }
                
                sqls = new List<string>();
            }
        }

        if (sqls.Count > 0)
        {
            U2.SQL.ExecuteSQL(string.Join("", sqls));
            sqls = new List<string>();
        }

        context.Response.Write("Total OK:" + intCount + ", end at: " + DateTime.Now.ToString() + "\r\n");

    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}